﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Globalization;
using System.Text.RegularExpressions;

namespace OlapProject
{
    class FreeAgentHouseParser: BaseParser
    {
        private string SHORT_NAME = "fh";
        private decimal POUND_TO_EURO = new decimal(1.16613076);
        private string[] typeKewords = { "penthouse", "flat", "bungalow", "semi-detached","castle","farm"
                                 ,"land","townhouse","detached","detached","town","town house","terraced"};

        private Dictionary<string, string> extraMap = new Dictionary<string, string>();

        public FreeAgentHouseParser()
        {
            extraMap["town"] = "townhouse";
            extraMap["town house"] = "townhouse";
            extraMap["terraced"] = "house";
        }

        protected override string getNextPageLink(HtmlDocument document)
        {
           HtmlNode nextPageNode = 
               document.DocumentNode.SelectSingleNode("//a[@title='Continue to next property listings page']");

           if (nextPageNode == null)
           {
               return base.getNextPageLink(document);
           }
           else
           {
               return "http://www.freehouseagent.com" + nextPageNode.GetAttributeValue("href", string.Empty);
           }
        }
        override protected void parsePage(HtmlAgilityPack.HtmlDocument document)
        {
            HtmlAgilityPack.HtmlDocument details = new HtmlDocument();
            foreach (HtmlNode advertNode in document.DocumentNode.SelectNodes("//div[@class='fleft pureh3 advertprice']"))
            {        

                 HtmlNode detailsNode = advertNode.Element("a");
                 string link = detailsNode.GetAttributeValue("href", string.Empty);
                 if (link != string.Empty)
                 {               
                    link = "http://www.freehouseagent.com" + link;

                    if (loader.downloadHtmlDocument(link, details))
                    {
                        PropertyVO property = parsePropertyVO(advertNode, details);
                        container.Add(property);
                    }
                 }          
             }    
        }

        private PropertyVO parsePropertyVO(HtmlNode advertNode, HtmlDocument details)
        {
            PropertyVO property = new PropertyVO();
            HtmlNode infoNode = details.GetElementbyId("extended");
            if (infoNode != null)
            {
                FreeAgentHouseParseUtil.prepareString(infoNode.InnerText);

                property.type = changeType(FreeAgentHouseParseUtil.getString("Property Type"));              
                property.bedrooms = FreeAgentHouseParseUtil.getInt("Number of Bedrooms");
                property.bathrooms = FreeAgentHouseParseUtil.getInt("Number of Bathrooms");                  
                
            }

            completeWithPrice(property, details);              
            completeWithCityAndCountry(property, advertNode.InnerText);
            property.source = SHORT_NAME;
            property.datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            return property;
        }

        private string changeType(string type)
            {
          
            if (type == string.Empty)
                return "unspecified";

            string newType = string.Empty;
            foreach (string key in typeKewords)
            {
                if (type.IndexOf(key) >= 0)
                {
                    newType = extraMap.ContainsKey(key) ? extraMap[key] : key;
                    break;
                }
            }

            return newType == string.Empty ? "other" : newType;
        }

        private void completeWithPrice(PropertyVO property, HtmlDocument document)
        {
            HtmlNode priceNode = document.DocumentNode.SelectSingleNode("//h3[@class='pricelabel']");
            if (priceNode != null)
            {
                string price = Utlis.removeExtraText(priceNode.InnerText);
                try
                {
                    property.price = Decimal.Parse(price, CultureInfo.InvariantCulture) * POUND_TO_EURO; 
                }
                catch
                {
                    property.price = 0;
                }
                  
            }
        }

        private void completeWithCityAndCountry(PropertyVO property, string text)
        {
            string[] elements = text.Replace(", ", ",").Split(',');
            if(elements.Length >= 2)
                property.city = elements[1].ToLower();
            if(elements.Length >= 3)
             property.country = elements[2].ToLower();    
        }


        public override string pageUrl 
        { 
            get 
            {
                return "http://www.freehouseagent.com/property-for-sale/p0";
            } 
        }


        public override string parseName
        {
            get  {  return "Free Agent House";  }
        }
        
    }
}
